package com.psa.tool.net;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.psa.tool.IGeneralEventCallback;
import com.psa.tool.SystemStatus;
import org.apache.http.Header;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetTool {
    public static final boolean ping(String ip) {
        String result = null;
        try {
            Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);
            InputStream input = process.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping------", "result content: " + stringBuffer.toString());

            int status = process.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    public static final boolean pingBaidu() {
        return ping("www.baidu.com");
    }

    public static void monitorNetworkStatus(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkRequest.Builder builder = new NetworkRequest.Builder();
            NetworkRequest request = builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                    .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).build();
            if (cm != null) {
                cm.requestNetwork(request, new ConnectivityManager.NetworkCallback(){
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        SystemStatus.networkIsOK = true;
//                        SystemStatus.showMessage("当前手机网络连接正常！");
                    }

                    @Override
                    public void onLost(Network network) {
                        super.onLost(network);
                        SystemStatus.networkIsOK = false;
//                        SystemStatus.showMessage("当前手机无法连接网络，请确定手机信号是否正常！");
                    }
                });
            }
        }
    }

    public static void getOnAsync(String url, final IGeneralEventCallback callback) {
        new AsyncHttpClient().get(url, buildResponseHandler(callback));
    }

    public static void postOnAsync(String url, RequestParams params, final IGeneralEventCallback callback) {
        new AsyncHttpClient().post(url, params, buildResponseHandler(callback));
    }

    public static TextHttpResponseHandler buildResponseHandler(final IGeneralEventCallback callback) {
        return new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                SystemStatus.showMessage(SystemStatus.MainActivity, s);
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                if (callback != null) {
                    callback.finished(null, s);
                }
            }
        };
    }

    public static Bitmap getURLImage(String url) {
        Bitmap bitmap = null;
        try {
            URL myUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)myUrl.openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
